package com.atguigu.juc.one;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLocDemo {

    private final Lock lock = new ReentrantLock();
    //A
    public  void a(){
        //加锁
        lock.lock();
        try {
            System.out.println("A开始："+Thread.currentThread().getName() );
            b();
            System.out.println("A结束："+Thread.currentThread().getName() );
        } finally {
            //解锁
            lock.unlock();
        }

    }
    //B
    public  void b(){
        //加锁
        lock.lock();
        try {
            System.out.println("B开始："+Thread.currentThread().getName() );
            c();
            System.out.println("B结束："+Thread.currentThread().getName() );
        } finally {
            //解锁
            lock.unlock();
        }

    }
    //C
    public    void c(){  //加锁
        lock.lock();
        try {
            System.out.println("C开始："+Thread.currentThread().getName() );
            System.out.println("C结束："+Thread.currentThread().getName() );
        } finally {
            //解锁
            lock.unlock();
        }

    }

    //测试可重入锁
    public static void main(String[] args) {
        ReentrantLocDemo reentrantLocDemo = new ReentrantLocDemo();
        //a，b，c三个方法是同一把锁
        //上述过程，在a方法里调b方法，在b方法里调c方法，可以实现，因为是可重入锁
        //只要是同一个线程，可以访问n多个同一把锁的方法，这个叫做可重入

        for (int i = 0; i <100 ; i++) {
            new Thread(()->{
                reentrantLocDemo.a();
            }).start();
        }


    }
}
